package org.example.controller;

import com.alibaba.fastjson.JSONObject;
import org.example.model.entity.User;
import org.example.response.ApiResponse;
import org.example.service.UserService;
import org.example.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public ApiResponse<String> login(@RequestBody JSONObject body) {
        // 输入验证
        if (body.isEmpty() || !body.containsKey("email") || !isValidEmail(body.getString("email"))) {
            return ApiResponse.error("请输入有效的邮箱！");
        }
        if (body.isEmpty() || !body.containsKey("password") || body.getString("password").isEmpty()) {
            return ApiResponse.error("请输入密码！");
        }

        String password = body.getString("password");
        String email = body.getString("email");

        try {
            User user = userService.authenticate(email, password); // 提取认证逻辑至服务层
            if (user != null) {
                HashMap<String, Object> tokenPayload = createTokenPayload(user); // 提取创建 token 的逻辑
                String token = JwtUtil.generateToken(tokenPayload);
                return ApiResponse.success(token);
            }
            return ApiResponse.error("用户名或密码错误");
        } catch (Exception e) {
            return ApiResponse.error("登录时发生错误，请稍后再试"+ e.getMessage());
        }
    }

    // 验证邮箱格式
    private boolean isValidEmail(String email) {
        // 正则表达式验证邮箱格式
        String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
        return email.matches(emailRegex);
    }

    // 提取创建 token 的逻辑
    private HashMap<String, Object> createTokenPayload(User user) {
        HashMap<String, Object> payload = new HashMap<>();
        payload.put("email", user.getEmail());
        payload.put("phone", user.getPhone());
        payload.put("userName", user.getUserName());
        payload.put("id", user.getId());
        return payload;
    }

}
